package com.tarena.lbs.attach.dao.repository.impl;


import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tarena.lbs.attach.dao.mapper.AttachMapper;
import com.tarena.lbs.attach.dao.repository.AttachRepository;
import com.tarena.lbs.attach.enums.AttachResultEnum;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.dto.AttachQrDTO;
import com.tarena.lbs.attach.pojo.param.AttachParam;
import com.tarena.lbs.attach.pojo.param.AttachQRParam;
import com.tarena.lbs.attach.pojo.param.AttachUpdateParam;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.attach.pojo.po.AttachPO;
import com.tarena.lbs.attach.pojo.query.AttachDeprecatedQuery;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.attach.utils.QRCodeUtil;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@Slf4j
@Repository
public class AttachRepositoryImpl implements AttachRepository {

    private static final int MAX_ID_BATCH_SIZE = 1000;
    @Autowired
    private AttachMapper attachMapper;
    @Override
    public AttachDTO insertAttachInfo(AttachParam attachParam) {
        return null;
    }

    @Override
    public List<AttachDTO> getAttachInfo(AttachQuery attachQuery) {
        return Collections.emptyList();
    }

    @Override
    public List<AttachDTO> batchGetAttachInfo(List<Integer> ids, Integer type) {
        if (ids == null || ids.isEmpty()) {
            // 可根据实际业务逻辑决定是否直接返回空列表或其他处理
            return Collections.emptyList();
        }
        // 防止因 id 数量过多导致 SQL 超长问题，可根据数据库配置调整最大值
        if (ids.size() > MAX_ID_BATCH_SIZE) {
            try {
                throw new BusinessException(AttachResultEnum.ID_BATCH_SIZE_LIMIT);
            } catch (BusinessException e) {
                throw new RuntimeException(e);
            }
        }
        LambdaQueryWrapper<AttachPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(AttachPO::getId, ids);
        List<AttachPO> result = attachMapper.selectList(wrapper);
        log.info("AttachServiceImpl.selectByIds:{}", result);
        return result.stream().map(attachPO -> {
            AttachDTO attachDTO = new AttachDTO();
            BeanUtils.copyProperties(attachPO, attachDTO);
            return attachDTO;
        }).collect(Collectors.toList());
    }

    @Override
    public int batchUpdateAttachByIdList(List<AttachUpdateParam> attachUpdateParamList) {
        return 0;
    }

    @Override
    public int deleteAttachByBusinessIdAndBusinessType(AttachUpdateParam attachUpdateParam) {
        return 0;
    }

    @Override
    public int deleteAttachById(Long id) {
        return 0;
    }

    @Override
    public int deleteAttachInfoByParam(AttachQuery attachQuery) {
        return 0;
    }

    @Override
    public int deleteAttachDeprecated(AttachDeprecatedQuery query) {
        return 0;
    }


    //若 id 为空则新增，id 不为空则批量更新
    @Override
public boolean batchUpdateBusiness(List<PicUpdateParam> params) {
    if (CollectionUtils.isEmpty(params)) {
        return false;
    }
    log.info("批量处理业务信息开始: {}", params);
    params.forEach(picUpdateParam -> {
        if (picUpdateParam.getId() == null) {
            // ID为空，执行新增操作
            AttachPO attachPO = new AttachPO();
            attachPO.setBusinessId(picUpdateParam.getBusinessId());
            attachPO.setBusinessType(picUpdateParam.getBusinessType());
            attachPO.setFileUuid(picUpdateParam.getFileUuid());
            // 其他字段赋值...
            attachMapper.insert(attachPO); // 调用插入方法
        } else {
            // ID不为空，执行更新操作
            AttachPO attachPO = new AttachPO();
            attachPO.setBusinessId(picUpdateParam.getBusinessId());
            attachPO.setBusinessType(picUpdateParam.getBusinessType());
            LambdaUpdateWrapper<AttachPO> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(AttachPO::getId, picUpdateParam.getId());
            wrapper.eq(AttachPO::getFileUuid, picUpdateParam.getFileUuid());
            attachMapper.update(attachPO, wrapper); // 调用更新方法
        }
    });
    return true;
}


    @Override
    public AttachDTO ByIdGatAttach(String logoId) {
        if (logoId ==  null){
            return null;
        }
        AttachDTO attachDTO = new AttachDTO();
        BeanUtils.copyProperties(attachMapper.selectById(logoId), attachDTO);
        return attachDTO;
    }

    @Override
    public AttachQrDTO generateQrCode(AttachQRParam attachQRParam) {
        log.info("二维码生成开始参数:{}", attachQRParam);
        String Uuid = UUID.randomUUID()+".jpg";
        //一,生成二维码
        QRCodeUtil.createCodeToFile(attachQRParam.getContent(),new File("C:\\Users\\15177\\home\\images\\dev\\lbs_attach"), Uuid);

        //二,保存数据
        //新增二维码信息到附件中
        PicUpdateParam param = new PicUpdateParam();
        param.setBusinessId(attachQRParam.getBusinessId());
        param.setBusinessType(attachQRParam.getBusinessType());
        param.setFileUuid(Uuid);
        //调用方法用于新增
        Boolean flag =batchUpdateBusiness(Collections.singletonList(param));
        log.info("二维码生成结果:{}",flag);

        //三,返回信息
        //新增完毕后返回二维码信息
        //同个uuid查询
        QueryWrapper<AttachPO> wrapper = new QueryWrapper<>();
        wrapper.eq("file_uuid",Uuid);
        AttachPO attachPO = attachMapper.selectOne(wrapper);
        //赋值属性返回信息
        AttachQrDTO attachQrDTO = new AttachQrDTO();
        attachQrDTO.setId(attachPO.getId());
        attachQrDTO.setFileUuid("http://localhost:8080/static/"+Uuid);
        attachQrDTO.setUrl(Uuid);
        return attachQrDTO;
    }
}
